package de.devisnik.eidle.app;

import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;

import de.devisnik.eidle.EidleActivator;
import de.devisnik.eidle.util.Parameters;

/**
 * This class controls all aspects of the application's execution
 */
public class Application implements IApplication {

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext)
	 */
	public Object start(final IApplicationContext context) {
		final String[] arguments = (String[]) context.getArguments().get(
				IApplicationContext.APPLICATION_ARGS);
		final Parameters parameters = new Parameters(arguments);

		context.applicationRunning();
		if (parameters.isPreviewMode()) {
			final Display previewDisplay = new Display();
			final Shell shell = Shell.win32_new(previewDisplay, parameters
					.getScreenHandle().intValue());
			shell.setMaximized(true);
			shell.setLayout(new FillLayout());
			final Canvas button = new Canvas(shell, SWT.NONE);
			final Image image = EidleActivator.getDefault().getImageRegistry()
					.get(EidleActivator.SPLASH_IMAGE_KEY);
			button.addPaintListener(new PaintListener() {

				public void paintControl(final PaintEvent e) {
					e.gc.setAntialias(SWT.ON);
					e.gc.drawImage(image, 0, 0, image.getBounds().width, image
							.getBounds().height, 0, 0, shell.getBounds().width,
							shell.getBounds().height);
				}
			});
			shell.open();
			while (!shell.isDisposed()) {
				if (!previewDisplay.readAndDispatch()) {
					previewDisplay.sleep();
				}
			}
			previewDisplay.dispose();
			return IApplication.EXIT_OK;

		} else {
			final Display display = PlatformUI.createDisplay();
			try {
				final int returnCode = PlatformUI.createAndRunWorkbench(
						display, new ApplicationWorkbenchAdvisor(parameters));
				if (returnCode == PlatformUI.RETURN_RESTART) {
					return IApplication.EXIT_RESTART;
				}
				return IApplication.EXIT_OK;
			} finally {
				display.dispose();
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.equinox.app.IApplication#stop()
	 */
	public void stop() {
		final IWorkbench workbench = PlatformUI.getWorkbench();
		if (workbench == null)
			return;
		final Display display = workbench.getDisplay();
		display.syncExec(new Runnable() {
			public void run() {
				if (!display.isDisposed())
					workbench.close();
			}
		});
	}
}
